#!/usr/bin/python3
#################################################################################
#    Python格式化usbmon原始数据，提高可读性                                     #
#    Copyright (C) 2021 Xu Ruijun                                               #
#                                                                               #
#    This program is free software; you can redistribute it and/or modify       #
#    it under the terms of the GNU General Public License as published by       #
#    the Free Software Foundation; either version 2 of the License, or          #
#    any later version.                                                         #
#                                                                               #
#    This program is distributed in the hope that it will be useful,            #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of             #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              #
#    GNU General Public License for more details.                               #
#                                                                               #
#    You should have received a copy of the GNU General Public License along    #
#    with this program; if not, write to the Free Software Foundation, Inc.,    #
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                #
#################################################################################

import os
import sys

def convert_fno(fni):
    bn = os.path.basename(fni)
    return os.path.join("proced", "p_" + bn)

def proc(fni, did, fno=None):
    if fno is None:
        fno = convert_fno(fni)
    print(fno)
    with open(fni, 'r') as fi, \
         open(fno, 'w') as fo:
        t_ = 0
        while True:
            line = fi.readline()
            if not line:
                break
            sp = line.split(' ')

            # 时间缀转时差
            t = int(sp[1])
            dt = t - t_
            t_ = t

            if sp[3][5:8] == did and sp[6] == '=':
                if sp[3][-1] == '1':
                    ch = '-'
                else:
                    ch = '='
                if sp[3][1] == 'i':
                    st = ch+'>'
                else:
                    st = '<'+ch
                write_str = f'{dt:010} ' + st + f' {sp[5]:>2} | ' + ' '.join(sp[7:])
                fo.write(write_str)
                print(write_str, end='')


files = [
('raw/reset.txt', '003'),
('raw/myreset.txt', '024'),
('raw/erase.txt', '031'),
('raw/down.txt', '005'),
('raw/verify.txt', '010'),
('raw/exit.txt', '031'),
('raw/freetime.txt', '031'),
('raw/notarget.txt', '031'),
]


if __name__ == '__main__':
    if not os.path.isdir("proced"):
        os.mkdir("proced")
    if len(sys.argv) > 1:
        fni = sys.argv[1]
        did = sys.argv[2]
        proc(fni, did)
    else:
        for fni, did in files:
            print()
            proc(fni, did)
